package payment.mobilepos.unionpay.com.metroguide.ui;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechRecognizer;

import io.reactivex.functions.Consumer;
import payment.mobilepos.unionpay.com.metroguide.R;
import payment.mobilepos.unionpay.com.metroguide.api.ApiConstants;
import payment.mobilepos.unionpay.com.metroguide.app.MyApplication;
import payment.mobilepos.unionpay.com.metroguide.bean.QueryFare;
import payment.mobilepos.unionpay.com.metroguide.utils.JsonParser;
import payment.mobilepos.unionpay.com.metroguide.utils.LogUtils;

/**
 * <pre>
 *     author : liuso
 *     e-mail : xxx@xx
 *     time   : 2018/12/24
 *     desc   :
 *     version: 1.0
 * </pre>
 */
public class MainPresenter extends MainContract.Presenter {

    private SpeechRecognizer mRecognizer;
    private String mEngineType = SpeechConstant.TYPE_CLOUD;
    private boolean mTranslateEnable = false;
    private Context mContext;
    private String mPrice;
    private String mPath;

    @Override
    public void init() {
        mContext = mView.getContext();
        mRecognizer = SpeechRecognizer.createRecognizer(mContext, mInitListener);
        setParam();
        JsonParser.getJson(mContext, true);
    }

    @Override
    public SpeechRecognizer getReconizer() {
        return mRecognizer;
    }


    /**
     * 参数设置
     *
     * @return
     */
    public void setParam() {
        String sampleDir = "baiduTTS";
        String mSamplePath = Environment.getExternalStorageDirectory().toString() + "/" + sampleDir;
        SharedPreferences mSharedPreferences = ((Activity) mView).getSharedPreferences(ApiConstants.KEY_SHARED_PREFERENCES_NAME,
                Activity.MODE_PRIVATE);
        // 清空参数
        mRecognizer.setParameter(SpeechConstant.PARAMS, null);

        // 设置听写引擎
        mRecognizer.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
        // 设置返回结果格式
        mRecognizer.setParameter(SpeechConstant.RESULT_TYPE, "json");
        this.mTranslateEnable = mSharedPreferences.getBoolean(MyApplication.getAppContext().getResources().getString(R.string.pref_key_translate), false);
        if (mTranslateEnable) {
            mRecognizer.setParameter(SpeechConstant.ASR_SCH, "1");
            mRecognizer.setParameter(SpeechConstant.ADD_CAP, "translate");
            mRecognizer.setParameter(SpeechConstant.TRS_SRC, "its");
        }

        String lag = mSharedPreferences.getString("iat_language_preference",
                "mandarin");
        if (lag.equals("en_us")) {
            // 设置语言
            mRecognizer.setParameter(SpeechConstant.LANGUAGE, "en_us");
            mRecognizer.setParameter(SpeechConstant.ACCENT, null);

            if (mTranslateEnable) {
                mRecognizer.setParameter(SpeechConstant.ORI_LANG, "en");
                mRecognizer.setParameter(SpeechConstant.TRANS_LANG, "cn");
            }
        } else {
            // 设置语言
            mRecognizer.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
            // 设置语言区域
            mRecognizer.setParameter(SpeechConstant.ACCENT, lag);

            if (mTranslateEnable) {
                mRecognizer.setParameter(SpeechConstant.ORI_LANG, "cn");
                mRecognizer.setParameter(SpeechConstant.TRANS_LANG, "en");
            }
        }
        //此处用于设置dialog中不显示错误码信息
        //mRecognizer.setParameter("view_tips_plain","false");

        // 设置语音前端点:静音超时时间，即用户多长时间不说话则当做超时处理
        mRecognizer.setParameter(SpeechConstant.VAD_BOS, mSharedPreferences.getString("iat_vadbos_preference", "4000"));

        // 设置语音后端点:后端点静音检测时间，即用户停止说话多长时间内即认为不再输入， 自动停止录音
        mRecognizer.setParameter(SpeechConstant.VAD_EOS, mSharedPreferences.getString("iat_vadeos_preference", "1500"));

        // 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mRecognizer.setParameter(SpeechConstant.ASR_PTT, mSharedPreferences.getString("iat_punc_preference", "0"));

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mRecognizer.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mRecognizer.setParameter(SpeechConstant.ASR_AUDIO_PATH, mSamplePath + "/outfile.wav");
    }

    /**
     * 初始化监听器。
     */
    private InitListener mInitListener = new InitListener() {

        @Override
        public void onInit(int code) {
            LogUtils.v("SpeechRecognizer init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                LogUtils.e("初始化失败，错误码：" + code);
            }
        }
    };


    @Override
    public void queryFare(String startStationKey, String endStationsKey) {
        mModel.queryFare(startStationKey, endStationsKey, "0")
                .subscribe(new Consumer<QueryFare>() {
                    @Override
                    public void accept(QueryFare queryFare) throws Exception {
                        mPrice = queryFare.getData().getP();
                        mView.updateView(mPrice, mPath);
                    }
                });
    }

    @Override
    public void queryPath(String startStationKey, String endStationsKey) {
        mModel.queryPath(startStationKey, endStationsKey, "0", mContext)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                         mPath = o.toString();
                        LogUtils.e("mpath=" + mPath);
                        mView.updateView(mPrice, mPath);
                    }
                });

    }


}
